//
//  NvProduceDlgViewController.m
//  NvSellerShow
//
//  Created by dx on 17/1/18.
//  Copyright © 2017年 Meicam. All rights reserved.
//

#import "NvProduceDlgViewController.h"
#import "NvsStreamingContext.h"
#import "AssetPackageObject.h"
#import "JMUnzipFile.h"
#import "UAProgressView.h"
#import "NvAssetModel.h"
#import "NvUploadManager.h"
#import "NvAssetManager.h"

@interface NvProduceDlgViewController () <NvsAssetPackageManagerDelegate,NSURLSessionDownloadDelegate>
{
    NSIndexPath *_selectedIndexPath;
    BOOL _needToPlayAfterSeek;
    NSTimer *timer;
}
@property (nonatomic, strong) NvsStreamingContext *streamingcontext;
@property (strong, nonatomic) UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UIView *playerView;

@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (nonatomic, strong) NSString * intallingThemePackagePath;
@property (nonatomic, strong) UAProgressView *downloadView;
@property (nonatomic, strong) NSMutableArray *sourceData;
@property (nonatomic, strong) NvUploadManager *manager;
@property (nonatomic, strong) UIButton *backBtn;
@property (nonatomic, strong) NSURLSession *session;
@property (nonatomic, strong) NSURLSessionDownloadTask *downloadTask;
@property (nonatomic, assign) BOOL hasCancel;
@end

static NSString* themeCellIdentifier = @"NvProduceTemplateCollectionViewCell";

@implementation NvProduceDlgViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self registProduceCell];
    [self setupUI];
    [self initNavigationBarView];
    
    [self resetPlayLabel];
    [self resetSlider];
    
    [self initPlayer];
    [self doPlayOrPause];
    self.streamingcontext.assetPackageManager.delegate = self;
    _selectedIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    NvProduceDlgViewController* __weak weakSelf = self;
    [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidEnterBackgroundNotification object:nil queue:[[NSOperationQueue alloc] init] usingBlock:^(NSNotification * _Nonnull note) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf doPause];
        });
    }];

    [self.collectionView reloadData];

    [self addObserverToPlayerItem:self.player.currentItem];

    [self addProgressObserver];

    [self addNotification];

    self.container.clipsToBounds = YES;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    [self initThemeArrayData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.isViewIn = NO;
    [self doPause];
    // 任务完成，取消NSURLSession
    [self.session invalidateAndCancel];
    // 释放会话
    self.session =nil;
}

- (void)setEditmode:(NvSSVideoCreateScale)editmode {
    if (editmode) {
        _editmode = editmode ;
    }
}

- (void)setupUI {
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.hasCancel = NO;
    
    self.downloadView = [[UAProgressView alloc]initWithFrame:CGRectMake(self.view.centerX_LL-60, self.view.centerY_LL-188, 120, 120)];
    self.downloadView.tintColor = UIColorHexRGB(@"#5bc2e5");
    self.downloadView.borderWidth = 1.0;
    self.downloadView.lineWidth = 2.0;
    self.downloadView.fillOnTouch = YES;
    UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 80.0, 30.0)];
    textLabel.font = [UIFont systemFontOfSize:24];
    textLabel.text = @"0";
    textLabel.textAlignment = NSTextAlignmentCenter;
    textLabel.textColor = UIColorHexRGB(@"#5bc2e5");
    textLabel.backgroundColor = [UIColor clearColor];
    self.downloadView.centralView = textLabel;
    
    self.downloadView.progressChangedBlock = ^(UAProgressView *progressView, CGFloat progress){
        [(UILabel *)progressView.centralView setText:[NSString stringWithFormat:@"%2.0f%%", progress * 100]];
    };
    [self.view addSubview:self.downloadView];
    [self.view addSubview:self.collectionView];
    [self.downloadView setHidden:YES];
    [self.view layoutIfNeeded];
    [self resetProduceBtnState];
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        //64 : navigationBar.height
        //75 : 底部按钮高度
        //20 : 上下的间距各10
        CGFloat collectionViewHeight = self.view.height_LL-self.view.width_LL-64-75-20;
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        flowLayout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
        flowLayout.minimumLineSpacing = 1;
        flowLayout.itemSize = CGSizeMake(collectionViewHeight-20, collectionViewHeight-10);

        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, self.view.width_LL+10, SCREEN_WIDTH, collectionViewHeight) collectionViewLayout:flowLayout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
    }
    return _collectionView;
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    if (_editmode == NvSSVideoCreateScaleSquare) {
        self.container.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH);
    } else if (_editmode == NvSSVideoCreateScaleHorizontal) {
        self.container.frame = CGRectMake(0, (SCREEN_WIDTH-SCREEN_WIDTH*9.0/16.0)/2, SCREEN_WIDTH, SCREEN_WIDTH*9.0/16);
    } else {
        self.container.frame = CGRectMake((SCREEN_WIDTH-SCREEN_WIDTH*9.0/16.0)/2, 0, SCREEN_WIDTH*9.0/16, SCREEN_WIDTH);
    }
    self.playCotrolView.bottom_LL = self.container.bottom_LL;
}

- (void)initThemeArrayData {
    _sourceData = [NSMutableArray array];
    self.manager = [NvUploadManager defaultManager];
    if (self.editmode == NvSSVideoCreateScaleSquare) {
        NvAssetModel *model = [[NvAssetManager new]getAssetsModelWithPath:NvAssetTheme];
        [_sourceData addObject:model];
    }
    
    [self.manager initThemeDataWithCompletionHandler:^(NSArray<NSDictionary *> *themeArray, NSString *errorDescription) {
//        //判断回执的错误信息
//        if ([errorDescription isEqualToString:@"error"]) {
//            [self JXDataFromLocal];
//        }
            //没错误
        [self JXDataFrom:themeArray];
    }];
}

- (void)JXDataFromLocal {
    NSString *assetPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"Assets/Theme"];
    NSString *themePath;
    if (self.editmode == NvSSVideoCreateScaleSquare) {
        themePath = [assetPath stringByAppendingPathComponent:@"squareVideo"];
    } else if (self.editmode == NvSSVideoCreateScaleHorizontal) {
        themePath = [assetPath stringByAppendingPathComponent:@"horizontalVideo"];
    } else {
        themePath = [assetPath stringByAppendingPathComponent:@"verticalVideo"];
    }
    NSArray *themeArr = [[NSFileManager defaultManager]contentsOfDirectoryAtPath:themePath error:nil];
    
    for (NSString *filePath in themeArr) {
        AssetPackageObject *object = [[AssetPackageObject alloc]initWithPath:[themePath stringByAppendingPathComponent:filePath] andAssetId:filePath andType:self.editmode];
        [_sourceData addObject:object];
    }
    if (_sourceData.count <= 0) {
        [Utils showMessageAlertWithTitle:@"提示" message:@"无网络,数据无法获取"];
        self.view.userInteractionEnabled = NO;
    } else {
        [self resetPlayer];
        [self doPlayOrPause];
        [self.collectionView reloadData];
        [self resetProduceBtnState];
    }
}

- (void)JXDataFrom:(NSArray *)receiveThemes {
    if (receiveThemes.count > 0) {
        for (NSDictionary *theme in receiveThemes) {
            int curScale = [[theme valueForKey:@"videoScale"]intValue];
            if (curScale == self.editmode) {
                AssetPackageObject *obje = [[AssetPackageObject alloc]initWithDictionary:theme];
                [_sourceData addObject:obje];
            }
        }
    }
    if (self.isViewIn) {
        if (self.editmode == NvSSVideoCreateScaleSquare && _sourceData.count == 1) {
            [Utils showMessageAlertWithTitle:@"提示" message:@"无网络,数据无法获取"];
            self.view.userInteractionEnabled = YES;
//            AVPlayerItem *item = [self getPlayerItem];
//            [self removeObserverFromPlayerItem:item];
        } else if (_sourceData.count <= 0) {
            [Utils showMessageAlertWithTitle:@"提示" message:@"无网络,数据无法获取"];
            self.view.userInteractionEnabled = NO;
//            AVPlayerItem *item = [self getPlayerItem];
//            [self removeObserverFromPlayerItem:item];
        }
    }

    [self resetPlayer];
    [self doPlayOrPause];
    [self.collectionView reloadData];
    [self resetProduceBtnState];
}

- (void)registProduceCell {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
    NSBundle *myBundle = [NSBundle bundleWithPath:path];
    [self.collectionView registerNib:[UINib nibWithNibName:@"NvProduceTemplateCollectionViewCell" bundle:myBundle]  forCellWithReuseIdentifier:themeCellIdentifier];
}

- (void)initNavigationBarView {
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    self.backBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
    [self.backBtn setBackgroundImage:[UIImage imageFromBundle:@"back_icon"] forState:UIControlStateNormal];
    [self.backBtn addTarget:self action:@selector(backBtnTouchedUpInside:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.backBtn];
    
    self.title = @"模版选择";
}

- (AssetPackageObject *)getPackageObjectWithIndexPath:(NSIndexPath *)indexPath {
    if (_sourceData.count <= 0 ) {
        return nil;
    }
    return (AssetPackageObject *)self.sourceData[indexPath.row];
}

- (void)installCurrentThemeWith:(NSString *)savePath andUUID:(NSString *)themeID andVerson:(NSInteger)version andLicense:(NSString *)licensePath{
    NvsAssetPackageManagerError  error;
    NSMutableString * returnPackageId =  [NSMutableString string];
    NSString * waitingInstallPackageId = themeID;
    NvsAssetPackageStatus packageStatus = [self.streamingcontext.assetPackageManager getAssetPackageStatus:waitingInstallPackageId type:NvsAssetPackageType_Theme];
    
    //package is already installed
    if(packageStatus != NvsAssetPackageStatus_NotInstalled) {
        NSInteger installedVersion = [self.streamingcontext.assetPackageManager getAssetPackageVersion:waitingInstallPackageId type:NvsAssetPackageType_Theme];
        //package need to update
        if(version > installedVersion) {
            error = [self.streamingcontext.assetPackageManager upgradeAssetPackage: savePath license:licensePath type:NvsAssetPackageType_Theme sync:NO assetPackageId:returnPackageId];
        }
    }
    //package need install
    else {
        error = [self.streamingcontext.assetPackageManager installAssetPackage: savePath license:licensePath type:NvsAssetPackageType_Theme sync:YES assetPackageId:returnPackageId];
    }
    NSLog(@"install error:%i",error);
}

- (NvsStreamingContext *)streamingcontext {
    if(_streamingcontext == nil) {
        _streamingcontext = [NvsStreamingContext sharedInstanceWithFlags:NvsStreamingContextFlag_Support4KEdit];
    }
    return _streamingcontext;
}

- (void)resetProduceBtnState {
    if (_selectedIndexPath.row == 0 && _editmode == NvSSVideoCreateScaleSquare) {
        [self.produceBtn setTitle:@"以此模版制作" forState:UIControlStateNormal];
        return;
    }
    AssetPackageObject *packageModel = [self getPackageObjectWithIndexPath:_selectedIndexPath];
    if (packageModel.state == NvAssetPackageStatePaiedNot) {
        [self.produceBtn setTitle:@"订购" forState:UIControlStateNormal] ;
    } else if (packageModel.state == NvAssetPackageStateDownloadNot) {
        [self.produceBtn setTitle:@"下载" forState:UIControlStateNormal];
    } else {
        [self.produceBtn setTitle:@"以此模版制作" forState:UIControlStateNormal];
    }
}

//是否需要更新本地模板数据
- (BOOL)needUpdateLocalThemeWith:(AssetPackageObject *)model {
    NSInteger localVersion = [self getLocalVersionPathWith:[model.fileSavePath stringByAppendingPathComponent:model.uuid]].integerValue;
    if (localVersion < [model.version integerValue]) {
        return YES;
    }
    return NO;
}

- (void)updateLocalThemeWith:(AssetPackageObject *)model {
    NSString *themePath = [NSString stringWithFormat:@"%@.theme",[self getLocalInfoPathWith:[model.fileSavePath stringByAppendingPathComponent:model.uuid] andKey:@"uuid"]];

//    [[NSFileManager defaultManager]removeItemAtPath:[model.fileSavePath stringByAppendingPathComponent:model.uuid]  error:nil];
    [[NSFileManager defaultManager]removeItemAtPath:themePath error:nil];
    [self.produceBtn setTitle:@"更新" forState:UIControlStateNormal];
}


- (IBAction)produceBtnTouchInSide:(UIButton *)sender {
    [self doPause];
    if (_sourceData.count <= 0) {
        return;
    }
    if ([sender.titleLabel.text isEqualToString:@"订购"]) {
        AssetPackageObject *model = [self.sourceData objectAtIndex:_selectedIndexPath.item];
        [self.manager orderThemeDataWith:model.themeUpdateUrl];
    } else if([sender.titleLabel.text isEqualToString:@"下载"] || [sender.titleLabel.text isEqualToString:@"更新"]) {
        NSString *curNet = [self currentNetWork];
        AssetPackageObject *model = [self.sourceData objectAtIndex:_selectedIndexPath.item];
        if ([curNet isEqualToString:@"NO-WIFI"]) {
            [Utils showMessageAlertWithTitle:@"下载失败" message:@"当前无网络"];
            return;
        } else if ([curNet isEqualToString:@"WIFI"]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.downloadView setHidden:NO];
                [self.downloadView setProgress:0];
                self.view.userInteractionEnabled = NO;
            });
            [self createThemeOutputPathWith:model];
            [self downloadThemeZipWith:model.zipDownUrl];
        } else {
            [Utils showConfirmAlertWithTitle:@"流量提醒" message:@"您正在使用移动网络,是否下载" yesTitle:@"确定" yesAction:^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.downloadView setHidden:NO];
                    [self.downloadView setProgress:0];
                    self.view.userInteractionEnabled = NO;
                });
                [self createThemeOutputPathWith:model];
                [self downloadThemeZipWith:model.zipDownUrl];
            } cancelTitle:@"取消" cancelAction:nil];
        }
    } else {
        UIStoryboard *story = [UIStoryboard storyboardWithName:@"ProcedureDlg" bundle:[Utils myBundle]];
        
        NvProcedureDlgViewController *modalView = [story instantiateViewControllerWithIdentifier:@"NvProcedureDlgViewController"];
        modalView.editmode = _editmode;
        if (_selectedIndexPath.row == 0 && _editmode == NvSSVideoCreateScaleSquare) {
            NvAssetModel *model = [self.sourceData objectAtIndex:_selectedIndexPath.row];
            [self installCurrentThemeWith:model.assetPackagePath andUUID:model.assetId andVerson:model.version andLicense:model.licensePath];
            modalView.themeUuid = model.assetId;
            modalView.themeName = model.displayName;
        } else {
            AssetPackageObject *model = [self getPackageObjectWithIndexPath:_selectedIndexPath];
            if ([self needUpdateLocalThemeWith:model]) {
                [self updateLocalThemeWith:model];
                return;
            }
            NSString *themePath = [NSString stringWithFormat:@"%@.theme",[self getLocalInfoPathWith:[model.fileSavePath stringByAppendingPathComponent:model.uuid] andKey:@"uuid"]];
            [self installCurrentThemeWith:themePath andUUID:model.uuid andVerson:[model.version integerValue] andLicense:[self getLocalInfoPathWith:[model.fileSavePath stringByAppendingPathComponent:model.uuid] andKey:@"licensePath"]];
            modalView.themeUuid = [self getPackageObjectWithIndexPath:_selectedIndexPath].uuid;
            modalView.themeName = [self getPackageObjectWithIndexPath:_selectedIndexPath].displayName;
        }
        [self.navigationController pushViewController:modalView animated:YES];
    };
}

- (void)resetPlayer {
    if(self.player && self.player.rate == 1) {
        [self doPause];
    }
    [self resetPlayLabel];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    [self removeObserverFromPlayerItem:self.player.currentItem];
    AVPlayerItem *playerItem = [self getPlayerItem];
    [self.player replaceCurrentItemWithPlayerItem:playerItem];
    [self addObserverToPlayerItem:playerItem];
    [self addNotification];
    [self resetSlider];
}

- (void)resetPlayLabel {
    self.timeLabel.text = @"00:00";
    self.totalTimeLabel.text = @"--:--";
    
    
}
- (void)resetSlider {
    self.slider.value = 0.0f;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark - AvPlayer初始化

-(void)initPlayer{
    //创建播放器层
    AVPlayerLayer *playerLayer=[AVPlayerLayer playerLayerWithPlayer:self.player];
    playerLayer.frame=self.container.bounds;
    playerLayer.videoGravity=AVLayerVideoGravityResizeAspectFill;//视频填充模式
    
    [self.container.layer addSublayer:playerLayer];
    
    [_container bringSubviewToFront:_playCotrolView];
}

/**
 *  初始化播放器
 *
 *  @return 播放器对象
 */
-(AVPlayer *)player{
    if (!_player) {
        _player=[AVPlayer playerWithPlayerItem:[self getPlayerItem]];
    }
    return _player;
}

-(AVPlayerItem *)getPlayerItem {
    NSURL *videoUrl;
    if (self.sourceData.count <= 0) {
        return nil;
    }
    if (_selectedIndexPath.row == 0 && _editmode == NvSSVideoCreateScaleSquare) {
        NvAssetModel *model = self.sourceData[_selectedIndexPath.row];
        videoUrl = [NSURL fileURLWithPath:model.previewVideoPath];
    } else {
        AssetPackageObject *model = self.sourceData[_selectedIndexPath.row];
        if (model.state == NvAssetPackageStateCanUse) {
            NSString *localVideoPath = [self getLocalInfoPathWith:[model.fileSavePath stringByAppendingPathComponent:model.uuid] andKey:@"preview"];
            videoUrl = [NSURL fileURLWithPath:localVideoPath];
        } else {
            videoUrl = [NSURL URLWithString:model.previewVideoUrl];
        }
    }
    AVPlayerItem *playerItem=[AVPlayerItem playerItemWithURL:videoUrl];
    
    return playerItem;
}

#pragma mark - 点击播放/暂停按钮
- (IBAction)playClick:(UIButton *)sender {
    [self doPlayOrPause];
}

- (void)doPlayOrPause {
    if(self.player.rate == 0){ //说明时暂停
        if(self.slider.value == self.slider.maximumValue)
            [self.player seekToTime:kCMTimeZero];
        [self doPlay];
    } else if(self.player.rate == 1){//正在播放
        [self doPause];
    }
}
- (void)doPlay {
    [self.playOrPause setImage:[UIImage imageFromBundle:@"player_stop"] forState:UIControlStateNormal];
    [self.player play];
}
- (void)doPause {
    [self.player pause];
    [self.playOrPause setImage:[UIImage imageFromBundle:@"player_play"]  forState:UIControlStateNormal];
    [timer invalidate];
}
#pragma mark - 通知
/**
 *  添加播放器通知
 */
-(void)addNotification{
    if (!self.player) {
        return;
    }
    //给AVPlayerItem添加播放完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(playbackFinished:)
                                                 name:AVPlayerItemDidPlayToEndTimeNotification
                                               object:self.player.currentItem];
}

/**
 *  播放完成通知
 *
 *  @param notification 通知对象
 */
-(void)playbackFinished:(NSNotification *)notification{
    [self.playOrPause setImage:[UIImage imageFromBundle:@"player_play"] forState:UIControlStateNormal];
    [self doPlayOrPause];
}

#pragma mark - 监控
/**
 *  给播放器添加进度更新
 */
-(void)addProgressObserver{
    if (!self.player) {
        return;
    }
    NvPlaySlider *slider = self.slider;
    UILabel *timelabel = self.timeLabel;
    //这里设置每秒执行一次
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 10.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        float current=CMTimeGetSeconds(time);
        
        if (current) {
            [slider setValue:current animated:YES];
            timelabel.text = [Utils stringWithTime:current];
        }
    }];
}

/**
 *  给AVPlayerItem添加监控
 *
 *  @param playerItem AVPlayerItem对象
 */
-(void)addObserverToPlayerItem:(AVPlayerItem *)playerItem {
    if (!playerItem) {
        return;
    }
    @try {
        //监控状态属性，注意AVPlayer也有一个status属性，通过监控它的status也可以获得播放状态
        [playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
        
        //监控网络加载情况属性
        [playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
    } @catch (NSException *exception) {
        
    }
}

/**
 *  通过KVO监控播放器状态
 *
 *  @param keyPath 监控属性
 *  @param object  监视器
 *  @param change  状态改变
 *  @param context 上下文
 */
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
   
    AVPlayerItem *playerItem=object;
    if (!playerItem) {
        return;
    }
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerStatus status= [[change objectForKey:@"new"] intValue];
        if(status == AVPlayerStatusReadyToPlay){
            self.playOrPause.enabled = YES;
            
            CMTime duration = playerItem.duration;// 获取视频总长度
            CGFloat totalSecond = duration.value / duration.timescale;// 转换成秒
            self.totalTimeLabel.text = [Utils stringWithTime:totalSecond];// 转换成播放时间
            [self.slider setMaximumValue:totalSecond];
        } else {
            self.playOrPause.enabled = NO;
        }
    } else if ([keyPath isEqualToString:@"loadedTimeRanges"]){
        NSArray *array=playerItem.loadedTimeRanges;
        CMTimeRange timeRange = [array.firstObject CMTimeRangeValue];//本次缓冲时间范围
        float startSeconds = CMTimeGetSeconds(timeRange.start);
        float durationSeconds = CMTimeGetSeconds(timeRange.duration);
        NSTimeInterval totalBuffer = startSeconds + durationSeconds;//缓冲总长度
        NSLog(@"共缓冲：%.2f",totalBuffer);
    }
}

- (void)removeObserverFromPlayerItem:(AVPlayerItem *)playerItem {
    if (!playerItem) {
        return;
    }
    [playerItem removeObserver:self forKeyPath:@"status"];
    [playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
}

- (IBAction)sliderTouchDown:(id)sender {
    _needToPlayAfterSeek = NO;
    
    if(self.player.rate == 1) {
        [self doPause];
        _needToPlayAfterSeek = YES;
    }
}

- (IBAction)sliderTouchUpInside:(id)sender {
    if(_needToPlayAfterSeek) {
        [self doPlay];
    }
}

- (IBAction)sliderValueChanged:(id)sender {
    //NSLog(@"slider Value changed");
    self.timeLabel.text = [Utils stringWithTime:self.slider.value];
    [self.player seekToTime:CMTimeMake(self.slider.value, 1.0)];
}

- (void)backBtnTouchedUpInside:(id)sender {
    [self.player pause];
    self.hasCancel = YES;
    self.streamingcontext.assetPackageManager.delegate = nil;
    self.streamingcontext.delegate = nil;
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Utility Methods

- (void)borderIsSelected:(BOOL)selected forView:(NvProduceTemplateCollectionViewCell *)cell {
    cell.coverImageView.layer.borderWidth = (selected) ? 2 : 0;
}

- (NvProduceTemplateCollectionViewCell *)cellAtIndexPath:(NSIndexPath *)indexPath {
    return (NvProduceTemplateCollectionViewCell*)[self.collectionView cellForItemAtIndexPath:indexPath];
}

#pragma mark <UICollectionViewDataSource>

//返回section中的cell个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.sourceData.count;
}

//返回cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NvProduceTemplateCollectionViewCell* themeCell = [self.collectionView dequeueReusableCellWithReuseIdentifier:themeCellIdentifier forIndexPath:indexPath];
    NSIndexPath *selectedIndexPath = _selectedIndexPath;
    BOOL isSelected = selectedIndexPath ? ([selectedIndexPath compare:indexPath] == NSOrderedSame) : NO;
    [self borderIsSelected:isSelected forView:themeCell];
    if (indexPath.row == 0 && _editmode == NvSSVideoCreateScaleSquare) {
        NvAssetModel *model = self.sourceData[indexPath.row];
        themeCell.label.text = model.displayName;
        themeCell.coverImageView.image = [UIImage imageWithContentsOfFile:model.imageCoverPath];
        [themeCell.themeStateImage setHidden:YES];
    } else {
        AssetPackageObject *model = self.sourceData[indexPath.row];
        [themeCell updateSubViewWith:model];
    }
    return themeCell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if([_selectedIndexPath isEqual:indexPath])
        return;
    NSIndexPath *oldIndexPath = _selectedIndexPath;
    if(oldIndexPath){
        [self borderIsSelected:NO forView:[self cellAtIndexPath:oldIndexPath]];
    }
    _selectedIndexPath = indexPath;
    [self.collectionView reloadItemsAtIndexPaths:@[oldIndexPath]];
    [self borderIsSelected:YES forView:[self cellAtIndexPath:indexPath]];
    [self resetPlayer];
    [self doPlayOrPause];
    [self resetProduceBtnState];
}

- (NSString *)getLocalInfoPathWith:(NSString *)path andKey:(NSString *)key{
    NSString *jsonInfoPath = [path stringByAppendingString:@"/info.json"];
    if([[NSFileManager defaultManager] fileExistsAtPath:jsonInfoPath]){
        //parse info.json in assetPath
        NSData *jdata = [[NSData alloc]initWithContentsOfFile:jsonInfoPath];
        NSError *error;
        NSDictionary *jsonObj = [NSJSONSerialization JSONObjectWithData:jdata options:0 error:&error];
        if(error || jsonObj == nil){
            return nil;
        }
        return [path stringByAppendingPathComponent:[jsonObj objectForKey:key]];
    }
    return nil;
}

- (NSNumber *)getLocalVersionPathWith:(NSString *)path{
    NSString *jsonInfoPath = [path stringByAppendingString:@"/info.json"];
    if([[NSFileManager defaultManager] fileExistsAtPath:jsonInfoPath]){
        //parse info.json in assetPath
        NSData *jdata = [[NSData alloc]initWithContentsOfFile:jsonInfoPath];
        NSError *error;
        NSDictionary *jsonObj = [NSJSONSerialization JSONObjectWithData:jdata options:0 error:&error];
        if(error || jsonObj == nil){
            return nil;
        }
        return [jsonObj objectForKey:@"version"];
    }
    return nil;
}

- (NSURLSession *)session {
    if (_session == nil) {
        // 创建配置对象 通常使用默认的配置就可以了
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        config.timeoutIntervalForRequest = 5;
        /*
         delegateQueue
         如果设置nil ， 代理在子线程回调，串行队列
         [[NSOperationQueue alloc]init] 还是在同一时间内只开启一条线程
         [NSOperationQueue mainQueue] 在主线程回调
         */
        _session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    }
    return _session;
}

#pragma mark - downThemeZipFromServer
- (void)downloadThemeZipWith:(NSString *)themeZipUrl {
    NSURL *Url = [NSURL URLWithString:themeZipUrl];
    // 创建会话
    self.downloadTask = [self.session downloadTaskWithURL:Url];
    // 恢复线程, 启动任务
    [self.downloadTask resume];
}
#pragma mark - NSURLSessionDataDelegate Function
// 下载了数据的过程中会调用的代理方法
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask  didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    CGFloat curValue = 1.0 * totalBytesWritten / totalBytesExpectedToWrite;
    [self.downloadView setProgress:curValue animated:YES];
}

// 请求完成，错误调用的代理方法
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    [self.downloadView setHidden:YES];
    if (self.hasCancel) {
        return;
    }
    if (error) {
        NSLog(@"%@",error.localizedDescription);
        [self reDownloadThemeModel];
    }
}

- (void)reDownloadThemeModel {
    [Utils showConfirmAlertWithTitle:@"下载失败" message:@"是否重新下载" yesTitle:@"继续" yesAction:^{
        AssetPackageObject *object = [self.sourceData objectAtIndex:_selectedIndexPath.item];
        [self.downloadView setHidden:NO];
        [self.downloadView setProgress:0];
        [self createThemeOutputPathWith:object];
        [self downloadThemeZipWith:object.zipDownUrl];
    } cancelTitle:@"取消" cancelAction:^{
        self.view.userInteractionEnabled = YES;
    }];
}

// 下载完成
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    // 下载成功
    // 注意 location是下载后的临时保存路径, 需要将它移动到需要保存的位置
    // JMUnzipFile 解压到指定的文件夹
    AssetPackageObject *model = [self.sourceData objectAtIndex:_selectedIndexPath.item];
    NvProduceTemplateCollectionViewCell *cell = [self cellAtIndexPath:_selectedIndexPath];
    JMUnzipFile *unZip = [[JMUnzipFile alloc]init];
    [unZip UnzipOpenFile:[location path]];
    if ([unZip UnzipFileTo:model.fileSavePath overWrite:true]) {
        [[NSFileManager defaultManager]removeItemAtPath:[location path] error:nil];
        model.state = NvAssetPackageStateCanUse;
        [cell updateSubViewWith:model];
        [self.sourceData enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            AssetPackageObject *curObj = obj;
            if ([curObj.displayName isEqualToString:model.displayName]) {
                obj = model;
            }
        }];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.downloadView setHidden:YES];
            self.view.userInteractionEnabled = YES;
            [self.collectionView reloadItemsAtIndexPaths:@[_selectedIndexPath]];
            [self resetProduceBtnState];
        });
    } else {
        [self reDownloadThemeModel];
    }
}

- (void)createThemeOutputPathWith:(AssetPackageObject *)object {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:object.fileSavePath]) {
        [fileManager createDirectoryAtPath:object.fileSavePath
               withIntermediateDirectories:YES
                                attributes:nil
                                     error:nil];
    }
}

#pragma mark - implement NvsAssetPackageManagerDelegate
- (void)didFinishAssetPackageInstallation:(NSString *)assetPackageId filePath:(NSString *)assetPackageFilePath type:(NvsAssetPackageType)assetPackageType error:(NvsAssetPackageManagerError)error {
    
    NSLog(@"install Package completed: %d %d %@\n %@", assetPackageType, error, assetPackageFilePath, assetPackageId);
    
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
    NSLog(@"\n\n\n\n\n---主图视频销毁了---\n\n\n\n\n");
    [self removeObserverFromPlayerItem:self.player.currentItem];
    //清空播放器
    self.player = nil;
}

- (NSString *)currentNetWork {
    UIApplication *app = [UIApplication sharedApplication];
    
    NSArray *children = [[[app valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews];
    
    int type = 0;
    for (id child in children) {
        if ([child isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
            type = [[child valueForKeyPath:@"dataNetworkType"] intValue];
        }
    }
    switch (type) {
        case 1:
            return @"2G";
            break;
        case 2:
            return @"3G";
            break;
        case 3:
            return @"4G";
            break;
        case 5:
            return @"WIFI";
            break;
        case 6:
            return @"WIFI";
            break;
        default:
            return @"NO-WIFI";//代表未知网络
            break;
    }
}

@end
